//
//  ViewController.swift
//  SwiftUtils
//
//  Created by Ink on 2022/1/26.
//

import UIKit
import ZMSwiftUtils

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
//        UserDefaultsTest().execute()
        
//        SwizzleTest().execute()
        
//        LayoutConstraintTest.execute(viewController: self)
        
//        if #available(iOS 14.0, *) {
//            ListViewTest.execute(viewController: self)
//        } else {
//            // Fallback on earlier versions
//        }
        
//        testHandler()
        
//        testUUID()
        

//        testViewFrame()
        
        testControl()
        
//        Task {
//            await cancelSleepingTask()
//        }
    }
    
//    override func viewDidAppear(_ animated: Bool) {
//        super.viewDidAppear(animated)
//
//        RouteTest().execute(viewController: self)
//    }
    
    
    
}

extension ViewController {
    
    func testProcessWeather() async {
        let records = await fetchWeatherHistory()
        let average = await calculateAverageTemperature(for: records)
        let response = await upload(result: average)
        print("Server response: \(response)")
    }
    
    func fetchWeatherHistory() async -> [Double] {
        (1...100_000_00).map { _ in Double.random(in: -10...30) }
    }

    func calculateAverageTemperature(for records: [Double]) async -> Double {
        let total = records.reduce(0, +)
        let average = total / Double(records.count)
        return average
    }

    func upload(result: Double) async -> String {
        "OK"
    }
    
    func cancelSleepingTask() async {

        let task = Task { () -> String in
            print("Starting")
            Task { await testProcessWeather() }
            await Task.sleep(1_000_000_000)
            try Task.checkCancellation()
            return "Done"
        }

        // 任务已经开始，但我们趁它处于休眠时把它取消掉
        task.cancel()
        
        do {
            let result = try await task.value
            print("结果: \(result)")
        } catch {
            print("任务已经被取消")
        }
        
        
    }
}

class NewDataController {
    @MainActor func save() {
        print("Saving data…")
    }
}

extension ViewController {
    
    func testControl() {
        
        let btn = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 100))).background(color: .red)
        
        view.addSubview(btn)
        
//        btn.addHandler(for: .allTouchEvents) {
//            print("allTouchEvents")
//        }
        
        btn.addHandler(for:.allEvents) {
            print("touchUpInside")
        }
        btn.removeTouchHandler(for: .touchUpInside)
    }
}

extension ViewController {
    
    func testViewFrame() {
        
        let view = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 100)))
        
        func printFrame(handler:(() -> Void)? = nil) {
            handler?()
            print(view.frame)
        }

        printFrame{ view.width = 300 }
        
        printFrame{ view.frame.size.height = 400}
        
        printFrame{ view.x = 100}
        
        let a: UIView? = view.subviews.first
        let b = a.or { UIView().background(color: .red) }
        print(b.backgroundColor ?? .blue)
    }
}

extension ViewController {
    func testUUID() {
        print(UUIDUtils.getUDID())
    }
}

extension ViewController {
    
    func testHandler() {
        
        enum EventType: String, HandlerEventType {
            case test
        }
        
        let eventBus = HandlerEventBus<EventType>()
        
        eventBus.register(type: .test) { data in
            guard let type = data as? EventType else {
                return
            }
            print(type.rawValue)
        }
        eventBus.trigger(type: .test, data: EventType.test)
    }
}

